﻿import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'dart:ui' as ui;
import 'diet_statistics_logic.dart';
import '../../../../gen/assets.gen.dart';
import '../../../../common/styles/theme_manager.dart';
import '../../../../entity/food_statistics.dart';

/// 饮食统计页面
class DietStatisticsView extends GetView<DietStatisticsLogic> {
  const DietStatisticsView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Stack(
          children: [
            // 渐变背景
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              height: 200.h,
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topRight,
                    end: Alignment.bottomRight,
                    colors: ThemeManager.to.backgroundGradientColors,
                    stops: const [0.1, 0.3, 0.7, 1.0],
                  ),
                ),
              ),
            ),

            // 主要内容
            Column(
              children: [
                // 自定义AppBar
                _buildAppBar(),

                // 日周月切换
                _buildTimePeriodSelector(),

                // 日期显示
                _buildDateDisplay(),

                // 可滚动内容
                Expanded(
                  child: SingleChildScrollView(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      child: Column(
                        children: [
                          SizedBox(height: 20.h),

                          // 饮食记录列表
                          _buildFoodRecordList(),

                          SizedBox(height: 32.h),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建自定义AppBar
  Widget _buildAppBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
              size: 20.sp,
            ),
          ),
          Expanded(
            child: Center(
              child: Text(
                '饮食记录',
                style: TextStyle(
                  fontSize: 18.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
          // 日历图标
          GestureDetector(
            onTap: () {
              // 跳转到日历页面
            },
            child: Assets.status.calendar.image(
              width: 24.w,
              height: 24.w,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建日周月切换器
  Widget _buildTimePeriodSelector() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        color: Colors.black.withOpacity(0.4),
        borderRadius: BorderRadius.circular(25.r),
      ),
      child: Obx(() => Row(
            children: [
              _buildPeriodButton('日', 0),
              _buildPeriodButton('周', 1),
              _buildPeriodButton('月', 2),
            ],
          )),
    );
  }

  /// 构建时间段按钮
  Widget _buildPeriodButton(String label, int index) {
    final isSelected = controller.state.selectedPeriod.value == index;
    return Expanded(
      child: GestureDetector(
        onTap: () => controller.changePeriod(index),
        child: isSelected
            ? Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(25.r),
                  color: Colors.transparent,
                  border: Border.all(
                    color: const Color(0xFFED5C2F),
                    width: 1,
                  ),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(24.r),
                  child: BackdropFilter(
                    filter: ui.ImageFilter.blur(sigmaX: 9, sigmaY: 9),
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 12.h),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            const Color(0xFFED5C2F).withValues(alpha: 0.3),
                            const Color(0xFFE33E10).withValues(alpha: 0.3),
                            const Color(0xFFE33E10).withValues(alpha: 0.3),
                          ],
                        ),
                      ),
                      child: Center(
                        child: Text(
                          label,
                          style: TextStyle(
                            fontSize: 17.sp,
                            fontWeight: FontWeight.w500,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              )
            : Container(
                padding: EdgeInsets.symmetric(vertical: 12.h),
                decoration: BoxDecoration(
                  color: Colors.transparent,
                  borderRadius: BorderRadius.circular(25.r),
                ),
                child: Center(
                  child: Text(
                    label,
                    style: TextStyle(
                      fontSize: 17.sp,
                      fontWeight: FontWeight.w500,
                      color: Colors.grey[400],
                    ),
                  ),
                ),
              ),
      ),
    );
  }

  /// 构建日期显示
  Widget _buildDateDisplay() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Obx(() {
        final statistics = controller.state.foodStatistics.value;
        String dateText = controller.state.currentDateText.value;

        // 如果是周或月，显示接口返回的日期范围
        if (controller.state.selectedPeriod.value == 1 || 
            controller.state.selectedPeriod.value == 2) {
          if (statistics?.dateStart != null && statistics?.dateEnd != null) {
            dateText = '${statistics!.dateStart} - ${statistics.dateEnd}';
          }
        } else if (controller.state.selectedPeriod.value == 0) {
          // 日视图显示接口返回的日期
          if (statistics?.recordDate != null && statistics?.weekName != null) {
            dateText = '${statistics!.recordDate}，${statistics.weekName}';
          }
        }

        return Text(
          dateText,
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        );
      }),
    );
  }

  /// 构建饮食记录列表
  Widget _buildFoodRecordList() {
    return Obx(() {
      final statistics = controller.state.foodStatistics.value;

      if (statistics == null) {
        return _buildEmptyState();
      }

      // 日视图：直接显示 foodVOS
      if (controller.state.selectedPeriod.value == 0) {
        final foodList = statistics.foodVOS ?? [];
        if (foodList.isEmpty) {
          return _buildEmptyState();
        }
        return Column(
          children: foodList
              .map((food) => Padding(
                    padding: EdgeInsets.only(bottom: 12.h),
                    child: _buildFoodCard(food),
                  ))
              .toList(),
        );
      }

      // 周/月视图：按日期分组显示 foodDayVOS
      final foodDayList = statistics.foodDayVOS ?? [];
      if (foodDayList.isEmpty) {
        return _buildEmptyState();
      }

      return Column(
        children: foodDayList.map((dayData) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 日期标题
              Padding(
                padding: EdgeInsets.only(bottom: 8.h, top: 8.h),
                child: Text(
                  '${dayData.recordDate ?? ''}，${dayData.weekName ?? ''}',
                  style: TextStyle(
                    fontSize: 15.sp,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              // 该日期的饮食记录
              ...((dayData.foodVOS ?? []).map((food) => Padding(
                    padding: EdgeInsets.only(bottom: 12.h),
                    child: _buildFoodCard(food),
                  ))),
            ],
          );
        }).toList(),
      );
    });
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Container(
      padding: EdgeInsets.all(40.w),
      child: Center(
        child: Column(
          children: [
            Icon(
              Icons.restaurant,
              color: Colors.grey[600],
              size: 48.sp,
            ),
            SizedBox(height: 16.h),
            Text(
              '暂无饮食记录',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建单个饮食卡片（参考StatusPage的样式）
  Widget _buildFoodCard(FoodVO food) {
    // 判断是否有图片
    final hasImage = food.imageUrl != null && food.imageUrl!.isNotEmpty;

    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: const Color(0xFF282528),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: const Color(0xFF212121),
          width: 1.0,
        ),
      ),
      child: Row(
        children: [
          // 餐食图片（有图片才显示）
          if (hasImage) ...[
            ClipRRect(
              borderRadius: BorderRadius.circular(12.r),
              child: Image.network(
                _buildImageUrl(food.imageUrl!),
                width: 80.w,
                height: 80.w,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    width: 80.w,
                    height: 80.w,
                    decoration: BoxDecoration(
                      color: Colors.grey[700],
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Center(
                      child: Icon(
                        Icons.restaurant,
                        color: Colors.grey[400],
                        size: 32.sp,
                      ),
                    ),
                  );
                },
              ),
            ),
            SizedBox(width: 12.w),
          ],

          // 餐食信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 第一行：食物名称和用餐类型标签
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        food.foodName ?? '未知食物',
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: Colors.white,
                          fontWeight: FontWeight.w500,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    if (food.mealType != null && food.mealType!.isNotEmpty) ...[
                      SizedBox(width: 8.w),
                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 8.w,
                          vertical: 4.h,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.grey[800],
                          borderRadius: BorderRadius.circular(4.r),
                        ),
                        child: Text(
                          food.getMealTypeText(),
                          style: TextStyle(
                            fontSize: 11.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                      ),
                    ],
                  ],
                ),
                SizedBox(height: 6.h),

                // 第二行：日期时间（如果有）
                if (food.recordTime != null && food.recordTime!.isNotEmpty) ...[
                  Text(
                    food.recordTime!,
                    style: TextStyle(
                      fontSize: 11.sp,
                      color: Colors.grey[500],
                    ),
                  ),
                  SizedBox(height: 8.h),
                ],

                // 第三行：营养信息（如果有）
                if (food.carbohydrate != null || food.protein != null || food.fat != null)
                  Row(
                    children: [
                      Expanded(
                        child: Row(
                          children: [
                            if (food.carbohydrate != null) ...[
                              Text(
                                '碳水: ',
                                style: TextStyle(
                                  fontSize: 11.sp,
                                  color: Colors.grey[500],
                                ),
                              ),
                              Text(
                                '${food.carbohydrate!.toStringAsFixed(0)}g',
                                style: TextStyle(
                                  fontSize: 11.sp,
                                  color: Colors.white,
                                ),
                              ),
                              SizedBox(width: 12.w),
                            ],
                            if (food.protein != null) ...[
                              Text(
                                '蛋白质: ',
                                style: TextStyle(
                                  fontSize: 11.sp,
                                  color: Colors.grey[500],
                                ),
                              ),
                              Text(
                                '${food.protein!.toStringAsFixed(0)}g',
                                style: TextStyle(
                                  fontSize: 11.sp,
                                  color: Colors.white,
                                ),
                              ),
                              SizedBox(width: 12.w),
                            ],
                            if (food.fat != null) ...[
                              Text(
                                '脂肪: ',
                                style: TextStyle(
                                  fontSize: 11.sp,
                                  color: Colors.grey[500],
                                ),
                              ),
                              Text(
                                '${food.fat!.toStringAsFixed(0)}g',
                                style: TextStyle(
                                  fontSize: 11.sp,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ],
                        ),
                      ),
                    ],
                  ),
              ],
            ),
          ),

          SizedBox(width: 12.w),

          // 卡路里显示
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                food.calories != null
                    ? food.calories!.toStringAsFixed(0)
                    : '--',
                style: TextStyle(
                  fontSize: 20.sp,
                  color: const Color(0xFFED5C2F),
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(
                'kcal',
                style: TextStyle(
                  fontSize: 11.sp,
                  color: const Color(0xFFED5C2F),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建图片URL
  String _buildImageUrl(String relative) {
    const String base = 'https://api.azlg.com/prod-api';
    if (relative.startsWith('http')) return relative;
    if (relative.startsWith('/')) return '$base$relative';
    return '$base/$relative';
  }

}
